import styles from "./logIn.module.sass"
import React, {PropsWithChildren, useRef, useState} from 'react'
import {Text, View} from "@tarojs/components";
import {logInByPhoneNumberAndPassword, logInByWechatOpenIdAndPhoneNumber} from "../apis/AuthorizationApi";
import authorizationStore from "../store/AuthorizationStore";
import Taro, {useLoad} from "@tarojs/taro";
import {Form, Input, Button, Checkbox, FormInstance, Space} from "@nutui/nutui-react-taro";
import MyNavigationBar from "../components/MyNavigationBar";
import {Eye, Marshalling} from "@nutui/icons-react-taro";

export interface LogInProps extends PropsWithChildren {

}

const RememberedEnterpriseCodeStorageKey = "RememberedEnterpriseCode"
const RememberedPhoneNumberStorageKey = "RememberedPhoneNumber"

const LogIn: React.FC<LogInProps> = ({}) => {
    let formRef = useRef<FormInstance | null>();
    useLoad((params) => {
        let rememberedEnterpriseCode = Taro.getStorageSync(RememberedEnterpriseCodeStorageKey);
        let rememberedPhoneNumber = Taro.getStorageSync(RememberedPhoneNumberStorageKey);
        formRef.current!.setFieldsValue({
            enterpriseCode: params.enterpriseCode || rememberedEnterpriseCode || "",
            phoneNumber: params.phoneNumber || rememberedPhoneNumber || ""
        })
    })

    const [confirming, setConfirming] = useState(false)

    const [checked, setChecked] = useState(false)

    const [seePassword, setSeePassword] = useState(false)
    return <>
        <MyNavigationBar>登录</MyNavigationBar>
        <View className={styles.formContainer}>
            <Form labelPosition={"top"} ref={ref => formRef.current = ref}
                  footer={<Button formType={"submit"} type={"primary"} loading={confirming} block>登录</Button>}
                  onFinish={async (values) => {
                      setConfirming(true)
                      try {
                          let logInResponse = await Taro.login();
                          if (logInResponse.errMsg === "login:ok") {
                              let phoneNumber = values.phoneNumber;
                              let enterpriseCode = values.enterpriseCode;
                              let header = process.env.NODE_ENV === "production" ? (await logInByWechatOpenIdAndPhoneNumber({
                                  wechatCode: logInResponse.code,
                                  phoneNumber: phoneNumber,
                                  password: values.password,
                                  enterpriseCode: enterpriseCode,
                              })).data : (await logInByPhoneNumberAndPassword({
                                  phoneNumber: phoneNumber,
                                  password: values.password,
                                  enterpriseCode: enterpriseCode,
                              })).data;
                              authorizationStore.setAuthorization(header)
                              Taro.setStorageSync(RememberedEnterpriseCodeStorageKey, enterpriseCode)
                              Taro.setStorageSync(RememberedPhoneNumberStorageKey, phoneNumber)
                              Taro.reLaunch({url: "/pages/index/index"})
                          } else {
                              Taro.showToast({
                                  icon: "error",
                                  title: `${logInResponse.errMsg}`
                              })
                          }
                      } finally {
                          setConfirming(false)
                      }
                  }}>
                <Form.Item required label={"企业代码"} name={"enterpriseCode"}
                           rules={[{required: true, message: "请输入企业代码"}]}>
                    <Input placeholder={"企业代码"} clearable type={"number"}/>
                </Form.Item>
                <Form.Item required label={"手机号"} name={"phoneNumber"}
                           rules={[{required: true, message: "请输入你的手机号"}]}>
                    <Input placeholder={"手机号码"} type={"number"} clearable/>
                </Form.Item>
                <Space justify={"between"}>
                    <Form.Item required label={"密码"} name={"password"}
                               rules={[{required: true, message: "请输入密码"}]}>
                        <Input placeholder={"密码"} type={seePassword ? "text" : "password"}/>
                    </Form.Item>
                    <div onClick={() => {
                        setSeePassword(!seePassword)
                    }} style={{paddingRight: 12, marginTop: 36}}>
                        {seePassword ? (
                            <Eye color="#1a1a1a"/>
                        ) : (
                            <Marshalling color="#1a1a1a"/>
                        )}
                    </div>
                </Space>
                <Form.Item>
                    <View className={styles.hint}>
                        <Text>温馨提示：本小程序仅供内部人员使用</Text>
                    </View>
                </Form.Item>
                <Form.Item name={"checked"} rules={[{
                    validator(_, value) {
                        return value
                    }, message: "请先同意以上协议"
                }]}>
                    <Checkbox checked={checked} onChange={value => {
                        setChecked(value)
                    }} label={<View className={styles.protocolHintContainer}><Text>阅读并同意</Text><Text
                        className={styles.link} onClick={(event) => {
                        event.stopPropagation()
                        Taro.navigateTo({
                            url: "/pages/privacyPolicy",
                        })
                    }}>《隐私政策》</Text><Text>和</Text><Text className={styles.link} onClick={(event) => {
                        event.stopPropagation()
                        Taro.navigateTo({
                            url: "/pages/serviceProvision",
                        })
                    }}>《服务条款》</Text></View>}/>


                </Form.Item>
            </Form>
        </View>
    </>
}

export default LogIn


